const workerpool = require('workerpool');


// 子任务类
class Subtask {
    constructor(result, index) {
        this.result = result;
        this.index = index;
        this.pool = workerpool.pool();
    }
    // 定义任务函数
    task = async (p1, p2) => {
        // 模拟耗时任务
        const delay = Math.floor(Math.random() * 4000) + 1000; // 3-10秒随机延迟
        await new Promise(resolve => setTimeout(resolve, delay));
        return { p1, p2, result: p1 + p2, delay };
    };
    
    async execute() {
        try {
            // 启动工作线程执行任务
            console.log(`任务 ${this.index} 启动`);
            const res = await this.pool.exec(this.task, [this.index, this.index * 2]);

            // 将结果写入共享数组
            this.result[this.index] = res;
            console.log(`任务 ${this.index} 完成，延迟：${res.delay}ms`);

            // 关闭线程池
            this.pool.terminate();
        } catch (err) {
            console.error(`任务 ${this.index} 失败:`, err);
        }
    }
}

// 顺序执行任务
const executeSequentially = async (taskCount) => {
    console.log("【顺序执行】开始...");
    const results = new Array(taskCount);

    for (let i = 0; i < results.length; i++) {
        const subtask = new Subtask(results, i);
        await subtask.execute();
    }

    console.log(`【顺序执行】所有任务完成。result: ${JSON.stringify(results)}`);
    return results;
};

// 并行执行任务
const executeInParallel = async (taskCount) => {
    console.log("【并行执行】开始...");
    const results = new Array(taskCount);

    // 创建空数组，不预设长度
    const tasks = [];
    for (let i = 0; i < taskCount; i++) {
        const subtask = new Subtask(results, i);
        // 收集任务执行的Promise
        tasks.push(subtask.execute());
    }

    await Promise.all(tasks);
    console.log(`【并行执行】所有任务完成。result: ${JSON.stringify(results)}`);
    return results;
};

// 主函数
const main = async () => {
    console.log("开始对比顺序执行和并行执行的耗时...\n");
    const taskCount = 3;

    let start = Date.now();
    await executeSequentially(taskCount);
    let end = Date.now();
    console.log(`顺序执行总耗时: ${end - start} 毫秒\n`);

    start = Date.now();
    await executeInParallel(taskCount);
    end = Date.now();
    console.log(`并行执行总耗时: ${end - start} 毫秒\n`);
};

// 运行主函数
main();
